package com.example.kotlincoroutine

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import org.junit.Test

class ChannelTest {
    @Test
    fun channel1(): Unit = runBlocking {
        /*
         * 生产一个消费一个，默认没有缓冲区
         */
        val channel = Channel<Int> {
            println("onUndeliveredElement: $it") // 这句没有打印
        }

        val producer = launch {
            var count = 0
            while (count < 300) {
                delay(10)
                println("生产第${++count} 个")
                channel.send(count)
            }
        }
        val consumer = launch {
            val iterator = channel.iterator()
            while (iterator.hasNext()) {
                val ele = iterator.next()
                println(ele)
            }
        }
        println("主协程结束") // 不会打印，因为consumer协程不会结束
    }
}